/*
  学习目标：掌握redux-thunk处理异步action
  步骤：
     0. 下包redux-thunk, 配置中间件
     1. action创建函数, 返回一个异步函数
     2. 异步函数的形参, 获取dispatch, dispatch调用传递Action对象
*/

import { TODO_DEL_BY_ID, TODO_UPDATE_BY_ID } from './actionTypes';

function loadNewTodoAPI() {
  const newTodo = {
    task: '异步返回的任务',
    id: Date.now(),
    isDone: false,
  };
  console.log('开始请求');
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('请求成功，2秒后,数据返回');
      resolve(newTodo);
    }, 2000);
  });
}
export const addAction = (newTask) => {
  // 1.  action创建函数, 返回一个异步函数
  return async (dispatch) => {
    // 2. 异步函数的形参, 获取dispatch, dispatch调用传递Action对象
    const newTodo = await loadNewTodoAPI();
    console.log('newTodo  ----->  ', newTodo);
    dispatch({ type: 'add', payload: newTodo });
  };
};

export const delByIdAction = (id) => {
  return {
    type: TODO_DEL_BY_ID,
    payload: id,
  };
};

export const updateByIdAction = (id) => ({
  type: TODO_UPDATE_BY_ID,
  payload: id,
});

export const clearDoneAction = () => ({
  type: 'clearDone',
});

export const updateTypeAction = (type) => ({
  type: 'updateType',
  payload: type,
});

export const setAllAction = (checked) => ({
  type: 'setAll',
  payload: checked,
});

// 了解-模拟实现原理
const myStore = {
  // 保存数据
  state: {},
  // 计算属性

  dispatch(action) {
    // 如果action是对象, 直接传给reducer计算, 💥走同步的逻辑
    if (typeof action === 'object') {
      myStore.reducer(myStore.state, action);
    }
    // 如果action是函数, 停止传给reducer 💥 走异步的逻辑
    if (typeof action === 'function') {
      action(myStore.dispatch);
    }
  },

  reducer(state, action) {
    console.log('reducer计算了  ----->  ');
    // 计算新的值
    // myStore.state = ....
  },
};
myStore.dispatch((dispatch) => {
  dispatch({ type: 'xxx', payload: 123 });
});
